package com.shuaigef.springbootinit.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuaigef.springbootinit.exception.BusinessException;
import com.shuaigef.springbootinit.mapper.CourseMapper;
import com.shuaigef.springbootinit.mapper.PaperCourseMapper;
import com.shuaigef.springbootinit.mapper.PaperMapper;
import com.shuaigef.springbootinit.mapper.UserExercisePaperMapper;
import com.shuaigef.springbootinit.model.entity.Paper;
import com.shuaigef.springbootinit.model.entity.PaperCourse;
import com.shuaigef.springbootinit.model.entity.UserExercisePaper;
import com.shuaigef.springbootinit.model.vo.GetPaperErrorRateVO;
import com.shuaigef.springbootinit.service.PaperService;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Administrator
 * 针对表【paper】的数据库操作Service实现
 * 2025-01-22 09:04:52
 */
@Service
@RequiredArgsConstructor
public class PaperServiceImpl extends ServiceImpl<PaperMapper, Paper> implements PaperService {

    private final PaperMapper paperMapper;
    private final CourseMapper courseMapper;
    private final PaperCourseMapper paperCourseMapper;
    private final UserExercisePaperMapper userExercisePaperMapper;

    /**
     * 获取试卷
     *
     * @param id 试卷id
     * @return 试卷
     */
    @Override
    @Cacheable(value = "paper", key = "#id")
    public Paper getPaper(String id) {
        QueryWrapper<Paper> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("paper_id", id);
        Paper paper = paperMapper.selectOne(queryWrapper);
        if (paper == null) {
            throw new BusinessException(400, "该题库不存在");
        }
        return paper;
    }

    /**
     * 查看所有题库
     *
     * @return 题库列表
     */
    @Override
    public List<Paper> getList() {
        List<Paper> paperList = paperMapper.selectList(null);
        if (paperList == null) {
            throw new BusinessException(400, "目前没有题库");
        }
        return paperList;
    }

    /**
     * 查看某门科的题库
     *
     * @param id 科id
     * @return 题库列表
     */
    @Override
    public List<Paper> getSubject(String id) {
        List<Paper> list = new ArrayList<>();
        List<PaperCourse> courseList = paperCourseMapper.selectList(new QueryWrapper<PaperCourse>()
                .eq("course_id", id));
        for (PaperCourse paperCourse : courseList) {
            list.add(paperMapper.selectOne(new LambdaQueryWrapper<Paper>()
                    .eq(Paper::getPaperId, paperCourse.getPaperId())));
        }
        if (ArrayUtil.isEmpty(list)) {
            throw new BusinessException(400, "该科目没有题库");
        }
        return list;
    }

    /**
     * 获取试卷的错误率情况
     *
     * @param paperId 试卷id
     * @return 错误率
     */
    @Override
    public List<GetPaperErrorRateVO> getPaperErrorRate(Integer paperId) {
        //找到该试卷的所有题目
        List<UserExercisePaper> userExercisePapers = userExercisePaperMapper.selectList(new LambdaQueryWrapper<UserExercisePaper>()
                .eq(UserExercisePaper::getPaperId, paperId));
        //按照题目id分组
        Map<Integer, List<UserExercisePaper>> collect = userExercisePapers.stream()
                .collect(Collectors.groupingBy(UserExercisePaper::getExerciseId));
        //计算错误率
        Map<Integer, Double> errorRateMap = collect.entrySet().stream()
                .collect(Collectors.toMap(Map.Entry::getKey, e -> 1 - e.getValue().stream()
                        .mapToInt(UserExercisePaper::getIsCorrect)
                        .average()
                        .orElse(0.0)));
        //找到错的人的id
        Map<Integer, List<Integer>> errorUserIds = collect.entrySet().stream()
                .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().stream()
                        .map(UserExercisePaper::getUserId).distinct().collect(Collectors.toList())));
        List<GetPaperErrorRateVO> result = new ArrayList<>();
        errorRateMap.forEach((key, value) -> {
            List<Integer> userIdList = errorUserIds.get(key);
            GetPaperErrorRateVO getPaperErrorRateVOBuilder = GetPaperErrorRateVO.builder()
                    .exerciseId(key)
                    .errorRate(value)
                    .userIdList(userIdList)
                    .build();

            result.add(getPaperErrorRateVOBuilder);
        });
        return result;
    }
}




